module Impressionizer
  module Impressionable
    def is_impressionable
      has_many :impressions, :as => :impressionable, :class_name => "Impressionizer::Impression"
      extend ClassMethods
      include InstanceMethods
    end

    module ClassMethods
      def most_impressions
        self.scoped.select{|obj| obj.impression_count > 0}.sort_by{|obj| -obj.impression_count}
      end

      def most_unique_impressions
        self.scoped.select{|obj| obj.impression_count > 0}.sort_by{|obj| -obj.unique_impression_count}
      end

      def impressions_for_action(action_name)
        Impressionizer::Impression.where(:action_name => action_name).count
      end
    end

    module InstanceMethods
      def impressionable?
        true
      end

      def impression_count
        impressions.size
      end

      def unique_impression_count
        impressions.group(:ip_address).size.size
      end
    end
  end
end